%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 30. 十二月 2021 17:56
%%%-------------------------------------------------------------------
-module(pack).
-author("admin").
-behaviour(pack_behav).
%% API
-export([pack/1]).


pack(MsgList) ->
  pack(lists:reverse(MsgList), <<>>).

pack([], BinAcc) -> {ok, BinAcc};
pack([MsgRec|MsgList], BinAcc)->
  Res = try
          [RecName|_] = tuple_to_list(MsgRec),
          case msg_rec_reflect:msg_id(RecName) of
            undef ->
              error;
            MsgId ->
              Pb_Mod = msg_rec_reflect:pb_mod(MsgId div 1000),
              BinData = Pb_Mod:encode_msg(MsgRec),
              Length = byte_size(BinData),
              NewBinAcc = <<Length:16, MsgId:16, BinData/binary, BinAcc/binary>>,
              {ok, NewBinAcc}
          end
        catch
          _:_ -> error
        end,
  case Res of
    {ok, NewBinAcc2} -> pack(MsgList, NewBinAcc2);
    _ -> error
  end.